<template>
  <div class="phone-form">
    <a-alert
      v-show="isLoginError"
      type="error"
      showIcon
      style="margin-bottom: 24px"
      message="验证码输入有误，请稍后重试"
    />
    <a-form :form="form" class="login-form" @submit="handleSubmit">
      <a-form-item>
        <a-input
          size="large"
          type="text"
          v-decorator="['phone', { rules: [{ required: true, message: '请输入手机号码' }] }]"
          placeholder="手机号"
          autocomplete="off"
        >
          <a-icon slot="prefix" type="mobile" style="color: rgba(0, 0, 0, 0.25)" />
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-input
          size="large"
          type="text"
          v-decorator="['identify', { rules: [{ required: true, message: '请输入短信验证码' }] }]"
          placeholder="短信验证码"
          autocomplete="off"
        >
          <a-icon slot="prefix" type="mail" style="color: rgba(0, 0, 0, 0.25)" />
          <span slot="suffix">
            <a-button
              type="link"
              :class="{ 'not-click': state.smsSendBtn }"
              size="small"
              @click.stop.prevent="handleSendCode"
              >{{ state.codeText }}</a-button
            >
          </span>
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-button
          type="primary"
          size="large"
          html-type="submit"
          class="login-form-sign"
          :loading="state.loginBtn"
          :disabled="state.loginBtn"
        >
          登录
        </a-button>
      </a-form-item>
    </a-form>
    <puzzle-verification
      width="400"
      height="240"
      blockSize="60"
      v-model="isShow"
      :onSuccess="handleSuccess"
    ></puzzle-verification>
  </div>
</template>

<script>
import { timeFix } from '@/utils/util'
import { mapActions } from 'vuex'
import PuzzleVerification from '@/components/puzzle-verification'
import { getSmsCaptcha } from '@/api/login'
export default {
  components: {
    PuzzleVerification,
  },
  data() {
    return {
      isShow: false,
      loginBtn: false,
      isLoginError: false,
      state: {
        time: 60,
        loginBtn: false,
        smsSendBtn: false,
        codeText: '获取验证码',
      },
      form: this.$form.createForm(this, { name: 'coordinated' }),
    }
  },
  methods: {
    ...mapActions(['Login']),
    handleSuccess() {
      const { state, form } = this
      this.isShow = false
      state.smsSendBtn = true
      const interval = window.setInterval(() => {
        if (state.time-- <= 0) {
          state.time = 60
          state.smsSendBtn = false
          state.codeText = '获取验证码'
          window.clearInterval(interval)
        } else {
          state.codeText = `${state.time}秒后重新发送`
        }
      }, 1000)

      const hide = this.$message.loading('短信验证码正在发送中...', 0)
      getSmsCaptcha({ _MobelNos: form.getFieldValue('phone') })
        .then((res) => {
          setTimeout(hide, 100)
          this.$notification['success']({
            message: '提示',
            description: '短信验证码发送成功，可能会有延后请耐心等待',
            duration: 8,
          })
          this.isShow = false
        })
        .catch((err) => {
          setTimeout(hide, 1)
          clearInterval(interval)
          state.time = 60
          state.smsSendBtn = false
          this.isShow = false
          this.requestFailed(err)
        })
    },
    handleSendCode(e) {
      e.preventDefault()
      const {
        form: { validateFields },
      } = this

      validateFields(['phone'], { force: true }, (err, values) => {
        if (!err) {
          this.isShow = true
        }
      })
    },
    handleSubmit(e) {
      e.preventDefault()
      const { Login, state } = this
      this.form.validateFields((err, values) => {
        if (!err) {
          state.loginBtn = true
          const loginParams = { ...values }
          delete loginParams.phone
          delete loginParams.identify
          loginParams.username = values.phone
          loginParams.password = values.identify
          loginParams.grant_type = 'password'
          Login(loginParams)
            .then((res) => this.loginSuccess(res))
            .catch((err) => this.requestFailed(err))
            .finally(() => {
              state.loginBtn = false
            })
          this.loginSuccess()
        }
      })
    },
    loginSuccess(res) {
      this.$router.push({ path: '/' })
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`,
        })
      }, 1000)
      this.isLoginError = false
    },
    requestFailed(err) {
      this.isLoginError = true
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试',
        duration: 4,
        style: {
          color: '#000',
        },
      })
    },
  },
}
</script>

<style lang="less" scoped>
.phone-form {
  .ant-form-item:nth-child(2) {
    margin-bottom: 0;
  }
  .login-form-sign {
    width: 100%;
    margin-top: 20px;
  }
  .not-click {
    color: #b3b9c7;
    pointer-events: none;
  }
  .code-tips {
    font-size: 12px;
  }
}
</style>
